<template>
  <div class="prompt-management">
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-dialog v-model="dialogVisible" title="新增提示词" width="60%">
        <el-form :model="form" label-width="100px">
          <el-form-item label="提示词名称">
            <el-input v-model="form.promptName" placeholder="请输入提示词名称" />
          </el-form-item>
          <el-form-item label="提示词内容">
            <el-input
              v-model="form.promptContent"
              type="textarea"
              :rows="8"
              placeholder="请输入提示词内容"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
      <el-button
        type="danger"
        :disabled="selectedIds.length === 0"
        @click="handleBatchDelete"
        style="margin-left: 10px"
      >
        批量删除
      </el-button>
    </div>

    <el-table :data="promptList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="promptId" label="ID" width="80" />
      <el-table-column prop="promptName" label="提示词名称" />
      <el-table-column prop="promptContent" label="提示词内容">
        <template #default="scope">
          <el-tooltip
            effect="dark"
            :content="scope.row.promptContent"
            placement="top"
            popper-class="no-max-width"
          >
            <span>{{
              scope.row.promptContent.length > 20
                ? scope.row.promptContent.substring(0, 20) + '...'
                : scope.row.promptContent
            }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)">修改</el-button>
          <el-button link type="danger" @click="handleSingleDelete(scope.row.promptId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import { ref, reactive, defineComponent } from 'vue'
import { getPromptList, deletePrompts, addPrompt, updatePrompt } from '@/api/promptApi'
import { ElMessage, ElMessageBox } from 'element-plus'

export default defineComponent({
  name: 'PromptManagementView',
  setup() {
    const promptList = ref([])
    const selectedIds = ref<number[]>([])

    interface PromptItem {
      promptId: number
      // 其他字段...
    }

    const handleSelectionChange = (selection: PromptItem[]) => {
      selectedIds.value = selection.map((item) => item.promptId)
    }

    const handleSingleDelete = async (id: number) => {
      try {
        await ElMessageBox.confirm('确定删除该提示词吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        await deletePrompts([id])
        ElMessage.success('删除成功')
        fetchPromptList()
      } catch (error) {
        console.error('删除失败:', error)
      }
    }

    const handleBatchDelete = async () => {
      if (!selectedIds.value.length) {
        ElMessage.warning('请选择要删除的提示词')
        return
      }

      try {
        await ElMessageBox.confirm('确定删除选中的提示词吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        await deletePrompts(selectedIds.value)
        ElMessage.success('删除成功')
        fetchPromptList()
      } catch (error) {
        console.error('删除失败:', error)
      }
    }

    const fetchPromptList = async () => {
      try {
        const res = await getPromptList()
        if (res.code === 200 && res.success) {
          promptList.value = res.data
        }
      } catch (error) {
        console.error('获取提示词列表失败:', error)
      }
    }

    const dialogVisible = ref(false)
    const form = reactive({
      promptId: '',
      promptName: '',
      promptContent: '',
    })

    const handleAdd = () => {
      form.promptId = ''
      form.promptName = ''
      form.promptContent = ''
      dialogVisible.value = true
    }

    interface PromptRow {
      promptId: number
      promptName: string
      promptContent: string
    }

    const handleEdit = (row: PromptRow) => {
      form.promptId = row.promptId.toString()
      form.promptName = row.promptName
      form.promptContent = row.promptContent
      dialogVisible.value = true
    }

    const submitForm = async () => {
      if (!form.promptName || !form.promptContent) {
        ElMessage.error('提示词名称和内容不能为空')
        return
      }
      try {
        console.log('正在提交表单数据:', form)
        let res
        if (form.promptId) {
          res = await updatePrompt(form)
        } else {
          res = await addPrompt(form)
        }
        console.log('接口返回:', res)
        if (res.code === 200 && res.success) {
          ElMessage.success(form.promptId ? '修改成功' : '新增成功')
          dialogVisible.value = false
          fetchPromptList()
          form.promptId = ''
          form.promptName = ''
          form.promptContent = ''
        } else {
          ElMessage.error(res.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        if (error instanceof Error) {
          ElMessage.error(error.message || '操作失败')
        } else {
          ElMessage.error('操作失败')
        }
      }
    }

    fetchPromptList()

    return {
      promptList,
      selectedIds,
      handleSelectionChange,
      handleBatchDelete,
      handleSingleDelete,
      handleAdd,
      handleEdit,
      submitForm,
      dialogVisible,
      form,
    }
  },
})
</script>

<style scoped>
.prompt-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-top: 20px;
}

.el-table::before {
  height: 0;
}

.el-table th {
  background-color: #f5f7fa;
  color: #909399;
}

.el-table__row:hover {
  background-color: #f5f7fa;
}
</style>
